/* 申请退款 */
import React, { useEffect, useState } from 'react';
import Taro, { useRouter } from '@tarojs/taro';
import { connect } from 'react-redux';
import { View, Image, Textarea } from '@tarojs/components';
import StandModal from '@/components/StandModal';
import TheButton from '@/components/Button/index';
import SelectLayout from '@/components/SelectLayout/index';
import pGo from '@/images/common/rightGray.png';
import ProductListMore from '../productListMore/index';
import './index.scss';

const ApplyRefund = ({
  dispatch,
  adjustmentBefore = {},
  detail = {},
  adjustmentBeforeTip = false,
}) => {
  const [reason, setReason] = useState(null);
  const [isOpenSelectReason, setIsOpenSelectReason] = useState(false);
  const [customRemark, setCustomRemark] = useState('');
  const router = useRouter();
  const { params = {} } = router;
  let { isModify = false, kind, orderId, mobile = '', isTakeOut = false } = params;

  const [num, setNum] = useState(0);
  const handleTextArea = (e) => {
    setNum(e.detail.value.length);
    setCustomRemark(e.detail.value || '');
  };

  const handleApplyReason = (date) => {
    setReason(date);
  };

  const handleClose = () => {
    dispatch({
      type: 'order/setAdjustmentBeforeTip',
      payload: false,
    });
    Taro.navigateBack();
  };

  const handleApplyAfterSale = ({ theKind, theOrderId }) => {
    dispatch({
      type: 'order/applyAfterService',
      payload: {
        kind: theKind,
        orderId: theOrderId,
      },
    });
  };

  const handleConcat = () => {
    if (mobile && mobile?.length > 0) {
      Taro.makePhoneCall({
        phoneNumber: mobile,
      });
    } else {
      Taro.showToast({
        title: '该商家未留电话号码',
        duration: 2000,
        icon: 'none',
      });
    }
    Taro.navigateBack();
  };

  useEffect(() => {
    if (isModify) {
      handleApplyAfterSale({ theKind: detail.kind, theOrderId: detail.orderId });
      let remark = detail.merchantRemark || '';
      let oldReason = JSON.parse(detail.reason || '{}');
      setCustomRemark(remark);
      setNum(remark.lenght);
      setReason(oldReason);
    } else {
      handleApplyAfterSale({ theKind: kind, theOrderId: orderId });
    }
    return () => {
      dispatch({
        type: 'order/setAdjustmentBeforeTip',
        payload: false,
      });
    };
  }, []);

  const handleSubmit = () => {
    dispatch({
      type: 'order/applyRefund',
      payload: {
        adjustment: {
          kind: isModify ? detail.kind : kind,
          orderId: isModify ? detail.orderId : orderId,
          reason,
          customRemark,
          orderAdjustId: isModify ? detail.id : undefined,
        },
      },
    });
  };

  let isTakeOutHere = isModify
    ? detail.distributionWay == 2 || detail.distributionWay == 3
      ? true
      : false
    : isTakeOut;

  return (
    <View className="ApplyRefund flex-column--center">
      <StandModal
        isOpened={adjustmentBeforeTip}
        cancelText="取消"
        confirmText="呼叫商家"
        onClose={handleClose}
        onCancel={handleClose}
        onConfirm={handleConcat}
        content="抱歉，该订单商家已接单，无法申请退款，如有疑问请联系商家"
      />
      {isTakeOutHere && (
        <ProductListMore
          product={adjustmentBefore.itemList}
          logisticsAmount={adjustmentBefore.logisticsAmount}
          className="mt20"
          title={adjustmentBefore.orgName}
        />
      )}
      <View className="box2 txt28 black085 refund">
        <View className="txt32 black085 blod">退款信息</View>
        <View className="flex-row-spaceBetween-center mt24">
          <View>退款原因</View>
          <View
            className="flex-row-spaceBetween-center"
            onClick={() => setIsOpenSelectReason(true)}
          >
            <View className={reason?.value?.lenght ? '' : 'gray'}>
              {reason?.value || '请选择（必填）'}
            </View>
            <Image className="arrow" src={pGo} />
          </View>
        </View>
        {isTakeOutHere ? (
          <>
            <View className="flex-row-spaceBetween-center mt32">
              <View>退款金额</View>
              <View className="red">¥{adjustmentBefore.maxTotalRefundAmount}</View>
            </View>
            <View className="flex-row-spaceBetween-center mt32">
              <View>退回账户</View>
              <View>{adjustmentBefore.refundTypeDescription}账户</View>
            </View>
            <View className="mt12 txt22 gray">
              最多可退{adjustmentBefore.maxTotalRefundAmount}（含运费
              {adjustmentBefore.logisticsAmount}）退款将返还实际支付金额
            </View>
          </>
        ) : (
          <>
            <View className="flex-row-spaceBetween-center mt32">
              <View>退款方式</View>
              <View>按照原路返还</View>
            </View>
            <View className="flex-row-spaceBetween-center mt32">
              <View>退款联系人</View>
              <View>{adjustmentBefore.refundUser || ''}</View>
            </View>
            <View className="flex-row-spaceBetween-center mt32">
              <View>联系方式</View>
              <View>{adjustmentBefore.refundMobile || ''}</View>
            </View>
          </>
        )}
      </View>
      {isTakeOutHere && (
        <View className="box2 mt20 remark">
          <View className="txt32 black085 blod">退款说明</View>
          <View className="mt12 flex-column rebox">
            <Textarea
              className="textarea"
              autoHeight
              placeholder="请描述申请售后服务的具体原因"
              placeholderClass="textPlaceHolder"
              maxlength={200}
              cursorSpacing={200}
              onInput={handleTextArea}
            />
            <View className="flex-row-end-center num">{num}/200</View>
          </View>
        </View>
      )}
      <View className="flex-row-center opArea">
        <TheButton txt="申请退款" handleOp={handleSubmit} disabled={reason?.value ? false : true} />
      </View>
      <SelectLayout
        isOpened={isOpenSelectReason}
        reasonList={adjustmentBefore.reasonList || []}
        handleClose={() => setIsOpenSelectReason(false)}
        handleSelected={handleApplyReason}
        title="申请理由"
        btnTxt="提交"
      />
    </View>
  );
};

export default connect(({ order }) => ({
  adjustmentBefore: order.adjustmentBefore,
  adjustmentBeforeTip: order.adjustmentBeforeTip,
  detail: order.adjustmentDetail,
}))(ApplyRefund);
